package com.aidansmeaton.weightmanager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;

import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.TimeFormatter;
import com.quietlycoding.android.picker.NumberPicker;

/** The first activity in the app. */
public class SetUpStartWeightActivity extends Activity {

	private static final int START = 1;
	private final int POUNDS_IN_STONE = 14;
	private final float POUNDS_IN_KILO = 2.2f;
	private final float KILOS_IN_POUND = 0.4536f;
	private final int MAX_POUNDS = 13;
	private final int MAX_STONES = 29;
	private final int MAX_KILOS = 199;
	private final int MIN_POUNDS = 0;
	private final int MIN_STONES = 0;
	private final int MIN_KILOS = 0;

	private DatabaseHelper db;
	private Calendar startDate;
	private String start_date;
	private int start_weight;
	private boolean imperial;

	private Button startDateButton;
	private NumberPicker startStonesPicker;
	private NumberPicker startPoundsPicker;
	private NumberPicker startKilosPicker;
	
	private LinearLayout imperialView;
	private LinearLayout metricView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setup_start_weight);

		setTitle("Setup - Start Weight");

		db = DatabaseHelper.getInstance(this);
		startDate = Calendar.getInstance();
		
		startStonesPicker = (NumberPicker) findViewById(R.id.start_stones_picker);
		startPoundsPicker = (NumberPicker) findViewById(R.id.start_pounds_picker);
		startKilosPicker = (NumberPicker) findViewById(R.id.start_kg_picker);
		
		start_weight = getSharedPreferences("Profile", 0).getInt("StartWeight",0);
		start_date = getSharedPreferences("Profile", 0).getString("StartDate", TimeFormatter.getDatabaseDateString(Calendar.getInstance()));
		
		imperial = getSharedPreferences("Profile", 0).getBoolean("Imperial",true);
		boolean start_units_imperial = getSharedPreferences("Profile", 0).getBoolean("StartUnits",imperial);
		
		// convert metric start weight to imperial
		if (imperial && !start_units_imperial){
			start_weight = ((int)(start_weight * POUNDS_IN_KILO));
		}
		
		// convert imperial start weight to metric
		if (!imperial && start_units_imperial){
			start_weight = ((int)(start_weight * KILOS_IN_POUND));
		}
		
		imperialView = (LinearLayout) findViewById(R.id.imperial);
		metricView = (LinearLayout) findViewById(R.id.metric);
		
		// Imperial
		if (imperial){
			metricView.setVisibility(View.GONE);
			imperialView.setVisibility(View.VISIBLE);
			startDateButton = (Button) findViewById(R.id.start_date_imperial);
			startStonesPicker.setRange(MIN_STONES, MAX_STONES);
			startPoundsPicker.setRange(MIN_POUNDS, MAX_POUNDS);
			startStonesPicker.setCurrent(start_weight / POUNDS_IN_STONE);
			startPoundsPicker.setCurrent(start_weight % POUNDS_IN_STONE);
		}
		
		// Metric
		else {
			metricView.setVisibility(View.VISIBLE);
			imperialView.setVisibility(View.GONE);
			startDateButton = (Button) findViewById(R.id.start_date_metric);
			startKilosPicker.setRange(MIN_KILOS, MAX_KILOS);
			startKilosPicker.setCurrent(start_weight);
		}
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			startDate.setTime(formatter.parse(start_date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		updateDisplay(); // date button

		// Stop keyboard popping up automatically
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

	}
	
	public void startDateClick(View v) {
		showDialog(START);
	}	

	private void updateDisplay() {
		startDateButton.setText(new StringBuilder()
				.append(TimeFormatter.getDayAsString(startDate.get(Calendar.DAY_OF_WEEK)))
				.append(" ")
				.append(startDate.get(Calendar.DAY_OF_MONTH))
				.append(" ")
				.append(TimeFormatter.getMonthAsString(startDate.get(Calendar.MONTH)))
				.append(" ")
				.append(startDate.get(Calendar.YEAR)));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case (START):
			return new DatePickerDialog(this, startDateSetListener,
					startDate.get(Calendar.YEAR),
					startDate.get(Calendar.MONTH),
					startDate.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener startDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			startDate.set(Calendar.YEAR, year);
			startDate.set(Calendar.MONTH, monthOfYear);
			startDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			updateDisplay();
		}
	};

	private void saveStartWeight() {
		
		// get weight and date from widgets
		String startDateString = TimeFormatter.getDatabaseDateString(startDate);
		int startWeight = (imperial)
			? (startStonesPicker.getCurrent() * POUNDS_IN_STONE) + startPoundsPicker.getCurrent()
			: startKilosPicker.getCurrent();		
				
		// save if valid input
		getSharedPreferences("Profile", 0).edit().putInt("StartWeight", startWeight).commit();
		getSharedPreferences("Profile", 0).edit().putString("StartDate", startDateString).commit();
		getSharedPreferences("Profile", 0).edit().putBoolean("StartUnits", imperial).commit();
		db.editWeightLog(startDateString, startWeight, (imperial) ? "i" : "m");
	}

	public void nextClick(View v) {
		saveStartWeight();
		finish();
		Intent setupIntent = new Intent(this, SetUpTargetWeightActivity.class);
		this.startActivity(setupIntent);
	}

	public void backClick(View v) {
		saveStartWeight();
		finish();
		Intent setupIntent = new Intent(this, SetUpWeightTypeActivity.class);
		this.startActivity(setupIntent);
	}

	public void laterClick(View v) {
		finish();
	}

}